package com.easycms.controller.rest;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import org.imgscalr.Scalr;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.easycms.common.FileUploadForm;
import com.easycms.entity.CmsUserAlbumAttach;
import com.easycms.service.CmsUserAlbumAttachService;

@Controller
@RequestMapping("/upload")
public class FileUploadController {
	
	private String storePath = "d:\\attach\\20131225\\";
	private static int THUMB_WIDTH = 77;
	private static int THUMB_HEIGHT = 57;
	
	@Resource(name = "cmsUserAlbumAttachServiceImpl")
	private CmsUserAlbumAttachService albumAttachService;
	
	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public String displayForm() {
		return "file_upload_form";
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(
			@ModelAttribute("uploadForm") FileUploadForm uploadForm,
					Model map) {
		
		List<MultipartFile> files = uploadForm.getFiles();

		List<String> fileNames = new ArrayList<String>();
		System.out.println("---------uploadForm.getUid()=" + uploadForm.getUid() + "-------------");
		System.out.println("---------uploadForm.getKey()=" + uploadForm.getKey() + "-------------");
		System.out.println("---------fileNames.size()=" + fileNames.size() + "-------------");
		System.out.println("---------files.size()=" + files.size() + "-------------");
		if(null != files && files.size() > 0) {
			for (MultipartFile multipartFile : files) {

				String fileName = multipartFile.getOriginalFilename();
				fileNames.add(fileName);
				//Handle file content - multipartFile.getInputStream()
				long size = multipartFile.getSize();
				System.out.println("---------fileName=" + fileName + "-------------");
				System.out.println("---------fileSize=" + size + "-------------");
				
				try {
					String fName = uploadFile(multipartFile, storePath);
					scaleAndSaveImageWithScalr(storePath + fName, storePath + "t" + fName, THUMB_WIDTH, THUMB_HEIGHT);
					CmsUserAlbumAttach attach = new CmsUserAlbumAttach();
					attach.setAlbumID(3);
					attach.setUserID(6);
					attach.setAttachDesc(fName);
					attach.setAttachExt("jpg");
					attach.setAttachFile(fName);
					attach.setAttachSize(Integer.valueOf(String.valueOf(size)));
					attach.setAttachStatus((short)1);
					attach.setCreateTime(new Date());
					attach.setUpdateTime(new Date());
					albumAttachService.save(attach);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		map.addAttribute("files", fileNames);
		return "file_upload_success";
	}
	
	/** 
     * @descrption 保存文件 
     * @author xdwang 
     * @create 2012-11-19下午4:17:36 
     * @param file 
     *            MultipartFile对象 
     * @param path 
     *            保存路径，如“D:\\File\\” 
     * @return 保存的全路径 如“D:\\File\\2345678.txt” 
     * @throws Exception 
     *             文件保存失败 
     */  
    public String uploadFile(MultipartFile file, String path)  
            throws Exception {  
  
        String filename = file.getOriginalFilename();  
        String extName = filename.substring(filename.lastIndexOf("."))  
                .toLowerCase();  
        String lastFileName = UUID.randomUUID().toString() + extName;  
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }  
        
        File temp = new File(path);  
        if (!temp.isDirectory()) {  
            temp.mkdir();  
        }
        // 图片存储的全路径  
        String fileFullPath = path + lastFileName;  
        FileCopyUtils.copy(file.getBytes(), new File(fileFullPath));  
        return lastFileName;  
    }  
    
    private void scaleAndSaveImageWithScalr(String sourceFile, String destFile,
			int width, int height) throws IOException {
		BufferedImage sourceImage = ImageIO.read(new File(sourceFile));
		BufferedImage destImage = Scalr.resize(sourceImage,
				Scalr.Method.QUALITY, width, height);
		writeJpeg(destImage, destFile, 0.9f);
	}

	private void writeJpeg(BufferedImage image, String destFile, float quality)
			throws IOException {
		ImageWriter writer = null;
		FileImageOutputStream output = null;
		try {
			writer = ImageIO.getImageWritersByFormatName("jpeg").next();
			ImageWriteParam param = writer.getDefaultWriteParam();
			param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			param.setCompressionQuality(quality);
			output = new FileImageOutputStream(new File(destFile));
			writer.setOutput(output);
			IIOImage iioImage = new IIOImage(image, null, null);
			writer.write(null, iioImage, param);
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (writer != null)
				writer.dispose();
			if (output != null)
				output.close();
		}
	}
}
